package com.pxmeta.app.controller.chat;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.pxmeta.chat.entity.dto.AddChatGroupDTO;
import com.pxmeta.chat.entity.dto.JoinGroupDTO;
import com.pxmeta.chat.entity.dto.SetDisturbDTO;
import com.pxmeta.chat.entity.dto.UpdateGroupDTO;
import com.pxmeta.chat.entity.vo.*;
import com.pxmeta.chat.service.IChatGroupApplyService;
import com.pxmeta.chat.service.IChatGroupService;
import com.pxmeta.chat.service.HuanxinService;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.service.IUserDisturbService;
import com.pxmeta.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/chatGroups")
@RequiredArgsConstructor
@Api(tags = "聊天群组", value = "聊天群组")
public class ChatGroupsController {

    private final HuanxinService huanxinService;
    private final IChatGroupService chatGroupService;
    private final IUserDisturbService userDisturbService;
    private final IChatGroupApplyService chatGroupApplyService;
    private final IUserService userService;


    @SaCheckLogin
    @ApiOperation(value = "根据圈子id获取群聊列表")
    @GetMapping("/getChatGroupsByCircleId")
    public AjaxResult<List<ChatGroupListVO>> getChatGroupsByCircleId(@RequestParam(required = false) Long circleId,
                                                                     @RequestParam(required = false) String name){
        Long userId = SecurityUtils.getUserId();
        List<ChatGroupListVO> list = chatGroupService.getCircleChatGroups(circleId, userId, name);
        return AjaxResult.success(list);
    }

    @SaCheckLogin
    @ApiOperation(value = "分页获取群聊列表")
    @GetMapping("/getChatGroupPage")
    public AjaxResult<List<ChatGroupListVO>> getChatGroupPage(@RequestParam(required = false) Long circleId,
                                                              @RequestParam(required = false) String keyword,
                                                              @RequestParam Integer page,
                                                              @RequestParam Integer size){
        Long userId = SecurityUtils.getUserId();
        List<ChatGroupListVO> list = chatGroupService.getChatGroupPage(circleId, userId, keyword, page, size);
        return AjaxResult.success(list);
    }


    @SaCheckLogin
    @ApiOperation(value = "获取群聊详情")
    @GetMapping("/getChatGroupInfo")
    public AjaxResult<ChatGroupDetailVO> getChatGroupInfo(@RequestParam Long chatGroupId){
        String username = SecurityUtils.getUsername();
        ChatGroupDetailVO chatGroup = chatGroupService.getChatGroupInfo(chatGroupId,username);
        return AjaxResult.success(chatGroup);
    }




    @PostMapping("/setDisturb")
    @ApiOperation("设置群免打扰")
    public AjaxResult setDisturb(@RequestBody SetDisturbDTO dto){
        Long userId = SecurityUtils.getUserId();
        userDisturbService.disturbChatGroup(userId, dto);
        return AjaxResult.success();
    }


    @GetMapping("/getNotDisturbChatGroups")
    @ApiOperation("获取免打扰群列表")
    public AjaxResult<GroupIdListVO> getNotDisturbChatGroup(){
        Long userId = SecurityUtils.getUserId();
        List<Long> groupIds = chatGroupService.getNotDisturbChatGroups(userId);
        GroupIdListVO vo = new GroupIdListVO();
        vo.setGroupIds(groupIds);
        return AjaxResult.success(vo);
    }

    @SaCheckLogin
    @ApiOperation("获取用户所有群聊（不分页）")
    @GetMapping("/getAllByUser")
    public AjaxResult getAllByUser(){
        String username = SecurityUtils.getUsername();
        JSONArray chatGroups = huanxinService.getUserChatGroups(username);
        return AjaxResult.success(chatGroups);
    }

    @SaCheckLogin
    @ApiOperation("申请加入群组")
    @PostMapping("/joinChatGroups")
    public AjaxResult joinChatGroups(@RequestBody AddChatGroupDTO dto){
        Long chatGroupId = dto.getChatGroupId();
        String reason = dto.getReason();
        Long userId = SecurityUtils.getUserId();
        chatGroupApplyService.joinGroup(userId,chatGroupId,reason);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("查看申请列表")
    @GetMapping("/getApplyList")
    public AjaxResult<ChatGroupApplyVO> getApplyList(@RequestParam Long chatGroupId,
                                                    @RequestParam(defaultValue = "1")Integer page,
                                                    @RequestParam(defaultValue = "20") Integer size){
        List<ChatGroupApplyDetailVO> applyList = chatGroupApplyService.getApplyList(chatGroupId, page, size);
        Integer applyCount = chatGroupApplyService.getApplyCount(chatGroupId);
        ChatGroupApplyVO vo = new ChatGroupApplyVO();
        vo.setApplyList(applyList);
        vo.setApplyCount(applyCount);
        return AjaxResult.success(vo);
    }

    @ApiOperation(value = "审核加入群聊")
    @GetMapping("/verifyJoin")
    @SaCheckLogin
    public AjaxResult verifyJoin(@RequestParam Long applyId,
                                 @RequestParam Integer status){
        chatGroupApplyService.verify(applyId,status);
        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation("删除申请")
    @DeleteMapping(value = "/deleteApply")
    public AjaxResult deleteApply(@RequestParam Long applyId){
        chatGroupApplyService.removeById(applyId);
        return AjaxResult.success();
    }



    @SaCheckLogin
    @ApiOperation("创建群聊")
    @PostMapping("/create")
    public AjaxResult create(@RequestBody CreateGroupVO vo){
        Long userId = SecurityUtils.getUserId();
        String groupId = chatGroupService.createChatGroups(userId, vo);
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("groupId", groupId);
        return AjaxResult.success(map);
    }

    @SaCheckLogin
    @ApiOperation("修改群资料")
    @PutMapping("/update")
    public AjaxResult update(@RequestBody UpdateGroupDTO dto){
        huanxinService.updateChatGroups(dto);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("删除群组")
    @DeleteMapping("/delete")
    public AjaxResult delete(String deleteGroup){
        chatGroupService.deleteChatGroup(deleteGroup);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("分页获取群组成员")
    @GetMapping("/getUserPage")
    public AjaxResult getUserPage(@RequestParam String groupId,
                                  @RequestParam Integer page,
                                  @RequestParam Integer size){
        JSONArray users = huanxinService.getUserPage(groupId, page, size);
        return AjaxResult.success(users);
    }


    @SaCheckLogin
    @ApiOperation("让用户加入群组")
    @PostMapping("/addUser")
    public AjaxResult addUser(@RequestBody JoinGroupDTO dto){
        String groupId = dto.getGroupId();
        List<String> userIds = dto.getUserIds();
        List<String> usernameList = userService.listByIds(userIds).stream().map(User::getUsername).collect(Collectors.toList());
        usernameList.forEach(username->huanxinService.addUserToChatGroups(groupId, username));
        chatGroupService.increaseUserCount(groupId, usernameList.size());
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("退出群聊")
    @DeleteMapping("/removeUser")
    public AjaxResult removeUser(String groupId){
        String username = SecurityUtils.getUsername();
        chatGroupService.signOutChatGroup(groupId, username);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("添加管理员")
    @PostMapping("/addAdmin")
    public AjaxResult addAdmin(@RequestParam String groupId, @RequestParam String adminUsername){
        huanxinService.addAdminToChatGroups(groupId, adminUsername);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("取消管理员")
    @DeleteMapping("/cancelAdmin")
    public AjaxResult cancelAdmin(@RequestParam String groupId, @RequestParam String adminUsername){
        huanxinService.cancelChatGroupsAdmin(groupId, adminUsername);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("群组转让")
    @PutMapping("/transfer")
    public AjaxResult transfer(String groupId, String newOwner){
        huanxinService.transferChatGroups(groupId, newOwner);
        return AjaxResult.success();
    }



}
